import time
from . import ConnPG
import psycopg2
from sanic.log import logger

class BrandTable:

    async def add_brand(self, brand_name):#添加祖类名，本系统为一级分类

        #参数检查

        if not brand_name:

            return {
                'status': -1,
                'errorCode': 107100,
                'errorMsg': '品牌名不能为空',
                'resultBody': None
            }

        sql = 'INSERT INTO brand(brand_name) VALUES (%s)'

        try:
            await ConnPG().execute(sql, (brand_name,))
        except psycopg2.errors.UniqueViolation:

            return {
                'status': -1,
                'errorCode': 107101,
                'errorMsg': '当前品牌名已经存在',
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "品牌添加成功",
            }

    async def select_all_brand(self):#查看所有商品

        sql = 'select * from brand'

        result = await ConnPG().fetchall(sql)

        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': result,
        }

    async def del_brand(self, brand_id):#删除brand

        #参数检查

        if not brand_id or not brand_id.isdecimal:

            return {
                'status': -1,
                'errorCode': 300100,
                'errorMsg': 'brand_id不能为空且为整数类型',
                'resultBody': None
            }

        sql = 'DELETE FROM brand WHERE id=%s'

        try:
            await ConnPG().execute(sql, (brand_id,))
        except psycopg2.errors.ForeignKeyViolation as e:

            # print(e)

            return {

                'status': -1,
                'errorCode': 300112,
                'errorMsg': str(e),
                'resultBody': None,
            }
        else:
        
            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': "brand删除成功",                                     
            }

    async def update_brand(self, brand_id, brand_name):#更新库房名称

        #参数检查
        if not all([brand_id, brand_name]) or not brand_id.isdecimal():


            return {
                'status': -1,
                'errorCode': 300100,
                'errorMsg': '接口有两个必传参数且brand_id为整数',
                'resultBody': None
            }

        sql = "UPDATE brand SET brand_name=%s WHERE id=%s"


        await ConnPG().execute(sql, (brand_name,brand_id))

    
        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': "brand修改成功",
        }


